package com.nmgydy.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class Functions {
	/** 获取当前时间（YYYY-MM-DD HH:SS:�?*/
	public static String getTimeNow(){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date now = new Date();
		return sdf.format(now);
	}
	/** 字符串转换成数字   */
	public static int stringToInt(String str){
		Integer i;
		try{
			i = Integer.parseInt(str);
		}catch(Exception e){
			return 1;
		}
		return i;
	}

	/** MD5加密 */
	public final static String encodeMD5(String s) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		try {

			byte[] strTemp = s.getBytes();
			MessageDigest mdTemp = MessageDigest.getInstance("MD5");
			mdTemp.update(strTemp);
			byte[] md = mdTemp.digest();
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			return null;
		}
	}

	/** 获取32位GUID */
	public static String getUUID() {
		return java.util.UUID.randomUUID().toString().replace("-", "");
	}

	/**
	 * 获取客户端IP地址
	 * @param request
	 * @return ip
	 */
	public static String getIPAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 是否为空
	 * @param str
	 * @return boolean
	 */
	public static boolean isEmpty(String str){
		if(str==null || "".equals(str)){
			return true;
		}
		return false;
	}

	/**
	 * 直接输出内容
	 * @param response
	 * @param str
	 */
	public static void responseWrite(HttpServletResponse response,String str){
		try {
			response.setHeader("Content-type", "text/html;charset=UTF-8");
			response.getWriter().write(str);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * URL编码
	 * @param str
	 */
	public static String URLEncode(String str){
		try {
			str = URLEncoder.encode(str,"UTF-8");
			return str;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * URL解码
	 * @param str
	 */
	public static String URLDecode(String str){
		try {
			str = URLDecoder.decode(str,"UTF-8");
			return str;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * 把字符串转换成UTF-8
	 * @param str
	 */
	public static String convertToUtf8(String str){
		String encode = "GB2312";      
		try {      
			if (str.equals(new String(str.getBytes(encode), encode))) {      
				return new String(str.getBytes(encode),"UTF-8");
			}      
			encode = "ISO-8859-1";      
			if (str.equals(new String(str.getBytes(encode), encode))) {      
				return new String(str.getBytes(encode),"UTF-8");    
			}      
			encode = "GBK";      
			if (str.equals(new String(str.getBytes(encode), encode))) {      
				return new String(str.getBytes(encode),"UTF-8");
			}
		} catch (Exception e) {   
			e.printStackTrace();
		} 
		return "";      
	}

	/** 通用的列表页过去方法 */
	public static List<?> list(HibernateDao hibernateDao,String hql,HttpServletRequest request){
		return list(hibernateDao,hql,new HashMap<String,Object>(),request);
	}
	public static List<?> list(HibernateDao hibernateDao,String hql,
			Map<String,Object> params,HttpServletRequest request){
		@SuppressWarnings("rawtypes")
		List list = new ArrayList();
		try{
			String pageSize = (String) request.getParameter("pageSize");
			String pageIndex = (String) request.getParameter("pageIndex");
			String sortField = (String) request.getParameter("sortField");
			String sortOrder = (String) request.getParameter("sortOrder");
			if(!Functions.isEmpty(sortField) && !Functions.isEmpty(sortOrder)){
				hql += " order by " + sortField + " " + sortOrder;
			}
			if(!isEmpty(pageSize) && !isEmpty(pageIndex)){
				list = hibernateDao.list(hql, params,Integer.parseInt(pageIndex)+1,
						Integer.parseInt(pageSize));
			}else{
				list = hibernateDao.list(hql,params);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return list;
	}

	/** 获取异常信息 */
	public static String getExceptionInfo(Exception e) {
		StringWriter stringWriter = new StringWriter();
		PrintWriter printWriter = new PrintWriter(stringWriter);
		e.printStackTrace(printWriter);
		return stringWriter.toString();
	}

	/** 去空格 */
	public static final String trim(Object value) {
		String rtn = "";
		if (value != null) {
			rtn = value.toString().trim();
		}
		return rtn;
	}

	/** 前补零 */
	public static String fillZero(int number, int length) {
		String numberString = String.valueOf(number);
		StringBuilder sb = new StringBuilder();
		int zeroLength = length - numberString.length();
		for (int i = 0; i < zeroLength; i++) {
			sb.append("0");
		}
		sb.append(numberString);
		return sb.toString();
	}

	/** 将字符串类型的数字转换为2个小数点（0.00）的字符串  */
	public static String formatDecimal(String lStr) {
		return formatDecimal(lStr, 2);
	}

	/** 将字符串类型的数字转换为指定小数点（0.*）的字符串 */
	public static String formatDecimal(String lStr, int number) {
		String rtn = null;
		BigDecimal bd = new BigDecimal(lStr);
		if (number > 0) {
			String fStr = "0.";
			for (int i = 0; i < number; i++) {
				fStr += "0";
			}
			rtn = new DecimalFormat(fStr).format(bd.setScale(number, BigDecimal.ROUND_HALF_UP).doubleValue());
		} else {
			rtn = bd.setScale(number, BigDecimal.ROUND_HALF_UP).toString();
		}
		return rtn;
	}

	/** 将double类型的数字转换为2个小数点（0.00）的字符串 */
	public static String formatDecimal(double lStr) {
		return formatDecimal(lStr, 2);
	}

	/** 将double类型的数字转换为指定小数点（0.*）的字符串 */
	public static String formatDecimal(double lStr, int number) {
		String rtn = null;
		BigDecimal bd = new BigDecimal(Double.toString(lStr));
		if (number > 0) {
			String fStr = "0.";
			for (int i = 0; i < number; i++) {
				fStr += "0";
			}
			rtn = new DecimalFormat(fStr).format(bd.setScale(number, BigDecimal.ROUND_HALF_UP).doubleValue());
		} else {
			rtn = bd.setScale(number, BigDecimal.ROUND_HALF_UP).toString();
		}
		return rtn;
	}
	
}
